/************tcpclient.c************************/

#include "communicationCapteurs.h"

int communicationCapteurs()
{
	/* Variable and structure definitions. */
	int sd, rc = sizeof(int);
	struct sockaddr_in serveraddr;
	char buffer[BufferLength];
	char server[255];
	//char temp;
	int totalcnt = 0;
	struct hostent *hostp;
	//char data[100] = "This is a test string from client lol!!! ";

	/* The socket() function returns a socket */
	/* descriptor representing an endpoint. */
	/* The statement also identifies that the */
	/* INET (Internet Protocol) address family */
	/* with the TCP transport (SOCK_STREAM) */
	/* will be used for this socket. */

	/******************************************/

	/* get a socket descriptor */
	if((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
	{
		perror("Client-socket() error");
		exit(-1);
	}
	else
		printf("Client-socket() OK\n");

	/*Use the default server name or IP*/
	strcpy(server, SERVER);

	memset(&serveraddr, 0x00, sizeof(struct sockaddr_in));
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(SERVPORT);

	if((serveraddr.sin_addr.s_addr = inet_addr(server)) == (unsigned long)INADDR_NONE)
	{
		/* When passing the host name of the server as a */
		/* parameter to this program, use the gethostbyname() */
		/* function to retrieve the address of the host server. */

		/***************************************************/

		/* get host address */
		hostp = gethostbyname(server);

		if(hostp == (struct hostent *)NULL)
		{
			printf("HOST NOT FOUND --> ");
			/* h_errno is usually defined */
			/* in netdb.h */
			printf("h_errno = %d\n",h_errno);
			printf("---This is a client program---\n");
			close(sd);
			exit(-1);
		}

		memcpy(&serveraddr.sin_addr, hostp->h_addr, sizeof(serveraddr.sin_addr));

	}

	/* After the socket descriptor is received, the */
	/* connect() function is used to establish a */
	/* connection to the server. */

	/***********************************************/

	/* connect() to server. */
	if((rc = connect(sd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)
	{
		perror("Client-connect() error");
		close(sd);
		exit(-1);
	}
	else
		printf("Connection established...\n");

	//int compteur = 0;

	//while(compteur++ < 5)
	for(;;)
	{
		//read data from server
		totalcnt = 0;
		totalcnt = recv(sd,buffer,sizeof(buffer),0 );
		if (totalcnt == -1) {
			// traitement de l'erreur
			perror("Client-read() error");
			close(sd);
			exit(-1);
		}

		buffer[totalcnt] = '\0';

		printf("Client-read() is OK-----read %d caracters\n", totalcnt);
		printf("Echoed data from the f***ing server: %s\n", buffer);

		pthread_t thread;

		if ( pthread_create(&thread, NULL, thread_traitement, (void *)buffer ) ){
			fprintf(stderr, "Erreur lors de pthread_create\n");
			break;
		}
	}

	/* When the data has been read, close() */
	/* the socket descriptor. */

	/****************************************/

	/* Close socket descriptor from client side. */
	close(sd);

	exit(0);

	return 0;
}

//function Cette fonction permet d'extraire une sous-chaîne de s comprise entre l'indice start et end.
char *str_sub (const char *s, unsigned int start, unsigned int end)
{
   char *new_s = NULL;

   if (s != NULL && start < end)
   {
/* (1)*/
      new_s = malloc (sizeof (*new_s) * (end - start + 2));
      if (new_s != NULL)
      {
         int i;

/* (2) */
         for (i = start; i <= end; i++)
         {
/* (3) */
            new_s[i-start] = s[i];
         }
         new_s[i-start] = '\0';
      }
      else
      {
         fprintf (stderr, "Memoire insuffisante\n");
         exit (EXIT_FAILURE);
      }
   }
   return new_s;
}


//tache de traitement
void *thread_traitement(void *msg)
{
	char* messageBrut = (char *)msg;

	printf("message avant traitement: %s\n", messageBrut);
	//decryptage du message
	char *sync_bytes = malloc (sizeof (*sync_bytes) * 4);
	char *h_SEQ_length= malloc(sizeof(*h_SEQ_length) * 2);
	char *org = malloc(sizeof(*org) * 2);
	char *data_bytes = malloc(sizeof(*data_bytes) * 8);
	char *id_bytes = malloc(sizeof(*id_bytes) * 8);
	char *status = malloc(sizeof(*status) * 2);
	char *check_sum = malloc(sizeof(*check_sum) * 2);


	/*sync_bytes = str_sub(messageBrut,0,3);
	printf("sync_bytes est : %s \n",sync_bytes);
	h_SEQ_length = str_sub(messageBrut,4,5);
	printf("h_SEQ-bytes est : %s \n",h_SEQ_length);
	org = str_sub(messageBrut,6,7);
	printf("org est : %s \n",org);*/
	data_bytes = str_sub(messageBrut,8,15);
	id_bytes = str_sub(messageBrut,16,23);
	status = str_sub(messageBrut,24,25);
	/*
	check_sum = str_sub(messageBrut,26,27);
	printf("check_sum %s \n",check_sum);*/

	if(!strcmp(id_bytes,"0021CC07")) 	//tester si c'est le capteur ID 0021CC07
	{
		printf("data_bytes : %s \n",data_bytes);
		printf("id_bytes : %s \n",id_bytes);
		printf("status est %s \n",status);

		/*switch((atoi)(data_bytes))
		{
		case 10000000:
			printf("bouton A1 \n ");
			break;
		case 30000000:
			printf("bouton A2 \n ");
			break;
		case 50000000:
			printf("bouton B1 \n ");
			break;
		case 70000000:
			printf("bouton B2 \n ");
			break;
		case 15000000:
			printf("bouton A1 et B1 \n ");
			break;
		case 17000000:
			printf("bouton A1 et B2 \n ");
			break;
		case 35000000:
			printf("bouton A2 et B1 \n ");
			break;
		case 37000000:
			printf("bouton A2 et B2 \n ");
			break;
		case 00000000:
			printf("bouton lache \n ");
			break;
		default:
			printf("data recu inconnu \n ");
			break;
		}*/



	}



	free(sync_bytes);
	free(h_SEQ_length);
	free(org);
	free(data_bytes);
	free(id_bytes);
	free(status);
	free(check_sum);

	//recherche dans la liste des capteurs
	//constitution du message traite
	//deposer le message dans la bal correspondante

	//usleep(1);
	//pthread_exit((void *)compteur);
	return 0;
}
